package com.ys.web.sys.oss.controller;


import com.ys.utils.base.j2se.DateHandler;
import com.ys.utils.base.j2se.Logger;
import com.ys.utils.base.j2se.StringHandler;
import com.ys.utils.datasource.DynamicDataSourceContextHolder;
import com.ys.web.sys.oss.model.Oss;
import com.ys.web.sys.oss.model.OssMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ 名称:oss管理器
 * @ 返回值:
 */
@Service
public class OssManager implements Runnable{

    /**oss持久化属性*/
    private Map<String, Oss> ossPoMap = new HashMap<>();
    @Autowired
    private OssMapper ossMapper;

    public Oss getOssPo(String business){
        return ossPoMap.get(business);
    }


    @PostConstruct
    private void init(){
        new Thread(this).start();
    }

    @Override
    public void run() {
        while (true){
            try {
                load();
                Thread.sleep(10000);
            } catch (Exception e) {
                Logger.error("加载oss上传配置失败",e);
            }
        }
    }

    private void load(){

        DynamicDataSourceContextHolder.setDataSourceKey("ysIm");
        List<Oss> list = ossMapper.list();
        if(StringHandler.isEmpty(list)){
            this.ossPoMap = new HashMap<>();
            return;
        }
        this.ossPoMap = list.stream().peek(x->x.setUrl(String.format("%s/%s",Logger.getEnv(),x.getUrl()))).collect(Collectors.toMap(Oss::getBusiness, x -> x));
    }

    public String loadUrl(String url, String param){
        return StringUtils.replaceOnce(url, "${"+param+"}", getParamValue(param));
    }

    private String getParamValue(String param){
        switch (param){
            case "day":
                return DateHandler.getDate(new Date(),"yyyyMMdd");
            default:
                return null;
        }
    }
    
}
